<template>
  <view class="bluetooth-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-icon" @click="goBack">
        <image src="/static/tabbar/back.png" mode="aspectFit"></image>
      </view>
      <view class="header-title">蓝牙设备</view>
    </view>
    
    <!-- 蓝牙状态栏 -->
    <view class="bluetooth-status">
      <view class="status-info" :class="{ active: bluetoothAvailable }">
        <text>蓝牙状态：{{ bluetoothAvailable ? '已开启' : '未开启' }}</text>
      </view>
      <button class="status-btn" @click="toggleBluetooth">
        {{ bluetoothAvailable ? '关闭蓝牙' : '开启蓝牙' }}
      </button>
    </view>
    
    <!-- 搜索控制 -->
    <view class="search-control">
      <button class="search-btn" @click="startScan" :disabled="!bluetoothAvailable || isScanning">
        {{ isScanning ? '正在搜索...' : '搜索设备' }}
      </button>
      <button class="search-btn stop" @click="stopScan" :disabled="!isScanning">
        停止搜索
      </button>
    </view>
    
    <!-- 设备列表 -->
    <scroll-view scroll-y class="device-list">
      <view v-if="devicesList.length === 0 && !isScanning" class="no-device">
        <text>暂无设备，请搜索</text>
      </view>
      
      <view 
        v-for="(device, index) in devicesList" 
        :key="index" 
        class="device-item"
        :class="{ connected: device.deviceId === connectedDeviceId }"
        @click="handleDeviceClick(device)"
      >
        <view class="device-info">
          <view class="device-name">{{ device.name || device.localName || '未知设备' }}</view>
          <view class="device-id">ID: {{ device.deviceId }}</view>
          <view class="device-rssi">信号强度: {{ device.RSSI }}dBm</view>
        </view>
        <view class="device-action">
          <text v-if="device.deviceId === connectedDeviceId">已连接</text>
          <text v-else>连接</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- 连接设备交互区域 -->
    <view class="device-control" v-if="connectedDeviceId">
      <view class="control-title">已连接设备</view>
      <view class="control-actions">
        <button class="control-btn" @click="sendTestData">发送测试数据</button>
        <button class="control-btn disconnect" @click="disconnectDevice">断开连接</button>
      </view>
    </view>
  </view>
</template>

<script>
import bluetoothManager from '../../src/utility/bluetooth.js';

export default {
  data() {
    return {
      bluetoothAvailable: false,
      isScanning: false,
      devicesList: [],
      connectedDeviceId: null
    }
  },
  onLoad() {
    // 检查蓝牙状态
    this.checkBluetoothState();
  },
  onUnload() {
    // 页面卸载时关闭蓝牙搜索
    if (this.isScanning) {
      bluetoothManager.stopScan();
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    // 检查蓝牙状态
    checkBluetoothState() {
      bluetoothManager.getBluetoothAdapterState()
        .then(res => {
          this.bluetoothAvailable = res.available;
          
          // 如果蓝牙已开启，刷新设备列表
          if (this.bluetoothAvailable) {
            this.devicesList = bluetoothManager.getDevicesList();
            this.connectedDeviceId = bluetoothManager.connectedDeviceId;
          }
        })
        .catch(err => {
          console.error('获取蓝牙状态失败', err);
          this.bluetoothAvailable = false;
        });
    },
    
    // 切换蓝牙状态
    toggleBluetooth() {
      if (this.bluetoothAvailable) {
        // 关闭蓝牙
        bluetoothManager.closeBluetoothAdapter()
          .then(() => {
            this.bluetoothAvailable = false;
            this.isScanning = false;
            this.devicesList = [];
            this.connectedDeviceId = null;
            
            uni.showToast({
              title: '蓝牙已关闭',
              icon: 'none'
            });
          })
          .catch(err => {
            console.error('关闭蓝牙失败', err);
          });
      } else {
        // 开启蓝牙
        bluetoothManager.initBluetooth()
          .then(() => {
            this.bluetoothAvailable = true;
            
            uni.showToast({
              title: '蓝牙已开启',
              icon: 'success'
            });
          })
          .catch(err => {
            console.error('初始化蓝牙失败', err);
          });
      }
    },
    
    // 开始搜索蓝牙设备
    startScan() {
      if (!this.bluetoothAvailable) {
        uni.showToast({
          title: '请先开启蓝牙',
          icon: 'none'
        });
        return;
      }
      
      this.isScanning = true;
      
      bluetoothManager.startScan()
        .then(() => {
          // 定时更新设备列表
          this.scanTimer = setInterval(() => {
            this.devicesList = bluetoothManager.getDevicesList();
          }, 1000);
          
          // 30秒后自动停止搜索
          setTimeout(() => {
            this.stopScan();
          }, 30000);
        })
        .catch(err => {
          console.error('开始搜索失败', err);
          this.isScanning = false;
        });
    },
    
    // 停止搜索蓝牙设备
    stopScan() {
      if (this.scanTimer) {
        clearInterval(this.scanTimer);
        this.scanTimer = null;
      }
      
      bluetoothManager.stopScan()
        .then(() => {
          this.isScanning = false;
          // 最后更新一次设备列表
          this.devicesList = bluetoothManager.getDevicesList();
        })
        .catch(err => {
          console.error('停止搜索失败', err);
          this.isScanning = false;
        });
    },
    
    // 处理设备点击
    handleDeviceClick(device) {
      // 如果已连接该设备，则不重复连接
      if (device.deviceId === this.connectedDeviceId) {
        uni.showToast({
          title: '已连接此设备',
          icon: 'none'
        });
        return;
      }
      
      // 如果已连接其他设备，先断开
      if (this.connectedDeviceId) {
        this.disconnectDevice();
      }
      
      // 停止搜索
      if (this.isScanning) {
        this.stopScan();
      }
      
      // 连接设备
      uni.showLoading({
        title: '正在连接...'
      });
      
      bluetoothManager.connectDevice(device.deviceId)
        .then(res => {
          uni.hideLoading();
          this.connectedDeviceId = device.deviceId;
          
          uni.showToast({
            title: '连接成功',
            icon: 'success'
          });
        })
        .catch(err => {
          uni.hideLoading();
          console.error('连接设备失败', err);
          
          uni.showToast({
            title: '连接失败',
            icon: 'none'
          });
        });
    },
    
    // 断开设备连接
    disconnectDevice() {
      if (!this.connectedDeviceId) {
        return;
      }
      
      uni.showLoading({
        title: '正在断开连接...'
      });
      
      bluetoothManager.disconnectDevice()
        .then(() => {
          uni.hideLoading();
          this.connectedDeviceId = null;
          
          uni.showToast({
            title: '已断开连接',
            icon: 'success'
          });
        })
        .catch(err => {
          uni.hideLoading();
          console.error('断开连接失败', err);
          
          uni.showToast({
            title: '断开连接失败',
            icon: 'none'
          });
        });
    },
    
    // 发送测试数据
    sendTestData() {
      if (!this.connectedDeviceId) {
        uni.showToast({
          title: '请先连接设备',
          icon: 'none'
        });
        return;
      }
      
      // 创建一个测试数据
      const buffer = new ArrayBuffer(123456);
      const dataView = new DataView(buffer);
      dataView.setUint8(0, 0x01); // 发送一个 0x01 指令
      
      uni.showLoading({
        title: '发送数据中...'
      });
      
      bluetoothManager.sendData(buffer)
        .then(() => {
          uni.hideLoading();
          
          uni.showToast({
            title: '发送成功',
            icon: 'success'
          });
        })
        .catch(err => {
          uni.hideLoading();
          console.error('发送数据失败', err);
          
          uni.showToast({
            title: '发送失败',
            icon: 'none'
          });
        });
    }
  }
}
</script>

<style lang="scss">
.bluetooth-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: var(--status-bar-height);
  box-sizing: border-box;
}

.header {
  position: relative;
  height: 90rpx;
  background-color: #42a5f5;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: content-box;
  
  .back-icon {
    position: absolute;
    left: 30rpx;
    width: 40rpx;
    height: 40rpx;
  }
  
  .back-icon image {
    width: 100%;
    height: 100%;
  }
  
  .header-title {
    font-size: 36rpx;
    font-weight: 500;
  }
}

.bluetooth-status {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .status-info {
    font-size: 28rpx;
    color: #999;
    
    &.active {
      color: #42a5f5;
    }
  }
  
  .status-btn {
    font-size: 26rpx;
    padding: 10rpx 30rpx;
    background-color: #42a5f5;
    color: #fff;
    border-radius: 30rpx;
    margin: 0;
  }
}

.search-control {
  display: flex;
  justify-content: space-between;
  padding: 0 20rpx;
  margin-bottom: 20rpx;
  
  .search-btn {
    flex: 1;
    font-size: 28rpx;
    background-color: #42a5f5;
    color: #fff;
    margin: 0 10rpx;
    border-radius: 10rpx;
    
    &.stop {
      background-color: #ff6b6b;
    }
    
    &[disabled] {
      background-color: #ddd;
      color: #999;
    }
  }
}

.device-list {
  flex: 1;
  padding: 0 20rpx;
  max-height: 60vh;
  
  .no-device {
    padding: 30rpx;
    text-align: center;
    color: #999;
    font-size: 28rpx;
  }
  
  .device-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    padding: 20rpx 30rpx;
    margin-bottom: 20rpx;
    border-radius: 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    &.connected {
      border-left: 8rpx solid #42a5f5;
    }
    
    .device-info {
      flex: 1;
      
      .device-name {
        font-size: 30rpx;
        font-weight: 500;
        margin-bottom: 8rpx;
      }
      
      .device-id, .device-rssi {
        font-size: 24rpx;
        color: #999;
        margin-top: 6rpx;
      }
    }
    
    .device-action {
      padding: 10rpx 30rpx;
      background-color: #42a5f5;
      color: #fff;
      border-radius: 30rpx;
      font-size: 26rpx;
    }
  }
}

.device-control {
  background-color: #fff;
  padding: 20rpx;
  margin: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .control-title {
    font-size: 30rpx;
    font-weight: 500;
    margin-bottom: 20rpx;
    text-align: center;
  }
  
  .control-actions {
    display: flex;
    justify-content: space-around;
    
    .control-btn {
      font-size: 26rpx;
      padding: 10rpx 40rpx;
      background-color: #42a5f5;
      color: #fff;
      border-radius: 30rpx;
      margin: 0;
      
      &.disconnect {
        background-color: #ff6b6b;
      }
    }
  }
}
</style> 